import '../models/book.dart';

List<ChapterInfo> splitChaptersInfo(String content) {
  final chapterReg = RegExp(
    r'(第[\d一二三四五六七八九十百千]+章[\s\S]*?)(?=第[\d一二三四五六七八九十百千]+章|\$)',
    multiLine: true,
  );
  final matches = chapterReg.allMatches(content);
  if (matches.isEmpty) {
    return [ChapterInfo(title: '正文', start: 0, end: content.length)];
  }
  final List<ChapterInfo> chapters = [];
  for (var i = 0; i < matches.length; i++) {
    final m = matches.elementAt(i);
    final start = m.start;
    final end =
        (i + 1 < matches.length)
            ? matches.elementAt(i + 1).start
            : content.length;
    final text = content.substring(m.start, m.end);
    final titleMatch = RegExp(r'第[\d一二三四五六七八九十百千]+章[^\n\r]*').firstMatch(text);
    final title = titleMatch?.group(0) ?? '章节';
    chapters.add(ChapterInfo(title: title, start: start, end: end));
  }
  return chapters;
}

String getChapterContent(String content, ChapterInfo info) {
  final text = content.substring(info.start, info.end);
  final titleMatch = RegExp(r'第[\d一二三四五六七八九十百千]+章[^\n\r]*').firstMatch(text);
  final title = titleMatch?.group(0) ?? info.title;
  final body = text.replaceFirst(title, '').trim();
  return body;
}
